import os
import subprocess
import time

import configparser

config = configparser.ConfigParser()

# 读取ini文件内容
config.read('properties.ini')

tempPath = config.get("default", "TEMP")
exePathPrefix = config.get("default", "EXE")

os.environ["CATBatchTraceDir"] = r"C:\XPDM\BatchServerImport\UUID"
os.environ["LOGDIR"] = r"C:\XPDM\BatchServerImport\LOGS-SERVER"

if not os.path.exists(os.environ["CATBatchTraceDir"]):
    os.makedirs(os.environ["CATBatchTraceDir"])
    print("创建CATBatchTraceDir")

if not os.path.exists(os.environ["LOGDIR"]):
    os.makedirs(os.environ["LOGDIR"])
    print("LOGDIR")

os.environ["CATTemp"] = tempPath
os.environ["exePathPrefix"] = exePathPrefix

os.environ["XPDMXMLFILENAME"] = r"D:\XPDM\BatchServerImport\Import\XPDMXML.xml"

# Path to the catstart.exe executable
catstart_path = os.environ["exePathPrefix"] + r"\win_b64\code\bin\catstart.exe"

if not os.path.exists(os.environ["CATTemp"]):
    print("Error: catstart.exe not found at the specified path.")
    exit(1)

command1 = [
    catstart_path,
    "-env", "Env",
    "-direnv", r"D:\Program Files\Dassault Systemes\B425\CATEnv",
    "-run", f"catbatchstarter -input \"C:\\Users\\Administrator\\Desktop\\XPDMXML.xml\" -output {os.environ['LOGDIR']} -type 1"
]

c1Started = False
try:
    # result = subprocess.run(command1, check=True, text=True, capture_output=True)
    result = subprocess.Popen(command1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    print("Command1 executed successfully!")
    print("Output:", result.stdout)
    pl = result.poll()
    while pl is not None:
        time.sleep(0.1)
    c1Started = True
except subprocess.CalledProcessError as e:
    print("Command failed with return code:", e.returncode)
    print("Error output:", e.stderr)
except FileNotFoundError:
    print("Error: catstart.exe not found at the specified path.")
except Exception as e:
    print("An unexpected error occurred:", str(e))

if not c1Started:
    print("Error: catstart.exe not found at the specified path.")
    exit(1)


# Write XPDMXMLFILENAME to BatchTaskEnvVar.txt
batch_task_env_var_path = os.path.join(os.environ["CATTemp"], "BatchTaskEnvVar.txt")
print(batch_task_env_var_path)
with open(batch_task_env_var_path, "w") as file:
    file.write(f"XPDMXMLFILENAME={os.environ['XPDMXMLFILENAME']}")

# Command to execute
command2 = [
    catstart_path,
    "-env", "Env",
    "-direnv", r"D:\Program Files\Dassault Systemes\B425\CATEnv",
    "-run", f"CATBatchStarter -input {os.environ['XPDMXMLFILENAME']} -type 2"
]

try:
    result2 = subprocess.run(command2, check=True, text=True, capture_output=True)
    print("Command2 executed successfully!")
    print("Output:", result2.stdout)
except subprocess.CalledProcessError as e:
    print("Command failed with return code:", e.returncode)
    print("Error output:", e.stderr)
except FileNotFoundError:
    print("Error: catstart.exe not found at the specified path.")
except Exception as e:
    print("An unexpected error occurred:", str(e))

# 实时打印第一个命令的输出和错误日志
def print_logs(process):
    while True:
        # 读取标准输出
        output = process.stdout.readline()
        if output:
            print("标准输出:", output.strip())
        # 读取标准错误
        error = process.stderr.readline()
        if error:
            print("标准错误:", error.strip())
        # 检查进程是否结束
        if process.poll() is not None:
            break
